package com.herench.bs.support;

import org.apache.cxf.endpoint.Client;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by ThinkPad on 2017/8/30.
 */

@Deprecated
public class SimpleWebServiceClientPool implements CleverContextAware, ServicePool<String, Client> {


    protected final ConcurrentMap<String, Client> pool = new ConcurrentHashMap<>();
    protected CleverClinicContext cleverClinicContext;

    @Override
    public CleverClinicContext getCleverClinicContext() {
        return this.cleverClinicContext;
    }

    @Override
    public void setCleverClinicContext(CleverClinicContext cleverClinicContext) {
        this.cleverClinicContext = cleverClinicContext;
    }

    /**
     * Adds the given service to the pool and acquires it.
     *
     * @param key    the key
     * @param client the service
     * @return the acquired service, is newer <tt>null</tt>
     * @throws IllegalStateException if the queue is full (capacity has been reached)
     */
    @Override
    public Client addAndAcquire(String key, Client client) {
        Client c = pool.get(key);
        if (c != null) {
            throw new RuntimeException(c + " wsclient已经存在.");
        }
        pool.put(key, client);
        return client;
    }

    /**
     * Tries to acquire the service with the given key
     *
     * @param key the key
     * @return the acquired service, or <tt>null</tt> if no free in pool
     */
    @Override
    public Client acquire(String key) {
        Client answer = pool.get(key);
        return answer;
    }

    /**
     * Releases the service back to the pool
     *
     * @param key    the key
     * @param client the service
     */
    @Override
    public void release(String key, Client client) {
        pool.put(key, client);
    }

    /**
     * remove this value which is abandon use the key
     *
     * @param key the key
     * @return
     */
    @Override
    public boolean remove(String key) {
        Client remove = pool.remove(key);
        return remove != null;
    }

    /**
     * query the pool to determine is exist this key
     *
     * @param key key
     * @return
     */
    @Override
    public boolean isExist(String key) {
        return pool.containsKey(key);
    }

    /**
     * Returns the current size of the pool
     *
     * @return the current size of the pool
     */
    @Override
    public int size() {
        return pool.size();
    }

    /**
     * Purges the pool.
     */
    @Override
    public void purge() {
        pool.clear();
    }

    /**
     * Returns all services of the pool
     */
    @Override
    public List<Client> getServices() {
        List<Client> services = new ArrayList<>();
        for (Map.Entry<String, Client> entry : this.pool.entrySet()) {
            services.add(entry.getValue());
        }
        return services;
    }
}
